package com.dminvoicemanager.services;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONStringer;

import com.dminvoicemanager.objects.LocationObj;
import com.dminvoicemanager.objects.UserObj;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

public class MinuteAlarm extends BroadcastReceiver implements LocationListener {

	private Context passcontext;
	double[] loc = new double[2];
	String imeistring;
	String date_to_string;
	ArrayList<String> arFinvHed = new ArrayList<String>();
	SQLiteDatabase mydb;

	boolean isGPSEnabled = false;
	boolean isNetworkEnabled = false;
	boolean canGetLocation = false;
	
	boolean isNotRegistered = true;

	double latitude;
	double longitude;

	private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
	private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute

	static String DATABASE_NAME = "dminvoicemanager.db";
	static String LOCATION_DB = "fRepGps";
	static String USER_DB = "fUserGps";
	String connectioURL = "123.231.13.199:1025";
	JSONStringer userJson = null;
	InputStream is = null;
	StringBuilder sb = null;
	String result = null;
	
	
	public MinuteAlarm() {

	}

	public MinuteAlarm(Context context, int initialDelaySeconds,
			int repeatEveryMinutes) {

		// Log.e("IN", "IN");

		passcontext = context;

		Date dateNow = new Date();
		Calendar c = Calendar.getInstance();
		SimpleDateFormat ddMMMyyFormat = new SimpleDateFormat(
				"yyyy-MM-dd HH:mm:ss");

		date_to_string = ddMMMyyFormat.format(dateNow);

		TelephonyManager telephonyManager = (TelephonyManager) context
				.getSystemService(Context.TELEPHONY_SERVICE);

		imeistring = telephonyManager.getDeviceId();

		AlarmManager alarmMgr = (AlarmManager) context
				.getSystemService(Context.ALARM_SERVICE);
		Intent intent = new Intent(context, MinuteAlarm.class);
		PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0,
				intent, PendingIntent.FLAG_UPDATE_CURRENT);

		Calendar time = Calendar.getInstance();
		time.setTimeInMillis(System.currentTimeMillis());
		time.add(Calendar.SECOND, initialDelaySeconds);

		alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP, time.getTimeInMillis(),
				1000 * 60 * repeatEveryMinutes, pendingIntent);
	}

	@Override
	public void onReceive(Context context, Intent intent) {

		Log.e("Alarm Fired", "Fired");
		String gmailacc="";

		mydb = context.openOrCreateDatabase(DATABASE_NAME,
				Context.MODE_PRIVATE, null);
		
		AccountManager accountManager = AccountManager.get(context); 
	    Account account = getAccount(accountManager);

	    if (account == null) {
	      gmailacc =  "";
	    } else {
	    	gmailacc = account.name;
	    }

		Location location = getLocation(context);
		Double lat, lon;
		try {
			lat = location.getLatitude();
			lon = location.getLongitude();
			
			float speed = location.getSpeed();

			loc[0] = lat;
			loc[1] = lon;

		} catch (NullPointerException e) {
			// e.printStackTrace();

			GetLocationNetGPS gl = new GetLocationNetGPS(context);
			loc = gl.GetLoc();

		}

		Log.e("Latitude", "" + loc[0]);
		Log.e("Longitude", "" + loc[1]);

		Date dateNow = new Date();
		Calendar c = Calendar.getInstance();
		SimpleDateFormat ddMMMyyFormat = new SimpleDateFormat(
				"yyyy-MM-dd HH:mm:ss");

		date_to_string = ddMMMyyFormat.format(dateNow);

		TelephonyManager telephonyManager = (TelephonyManager) context
				.getSystemService(Context.TELEPHONY_SERVICE);

		imeistring = telephonyManager.getDeviceId();
		
		String tnumber=telephonyManager.getLine1Number();
		

		LocationChange("" + loc[0], "" + loc[1], date_to_string, imeistring,
				"0");
		
		int crsr_user_count = getUserIsRegistered(context,imeistring,tnumber,gmailacc);
		
		///Make Sure The Same Record doesnt get included in DB
		if(crsr_user_count==0){
			UserChange(imeistring, tnumber, gmailacc, "0");
		}
		
		ArrayList<UserObj> UserObjArr = new ArrayList<UserObj>();
		
		Cursor user_crsr = getDBdataUser(context);
		
		if (user_crsr != null) {

			while (user_crsr.moveToNext()) {
				int _id = user_crsr.getInt(user_crsr.getColumnIndex("_id"));
				String imei_no = user_crsr.getString(user_crsr
						.getColumnIndex("imei_no"));
				String phone_no = user_crsr.getString(user_crsr
						.getColumnIndex("phone_no"));
				String email_add = user_crsr.getString(user_crsr
						.getColumnIndex("email_add"));
				String sync_state = user_crsr.getString(user_crsr
						.getColumnIndex("sync_state"));

				UserObjArr.add(new UserObj(_id, imei_no, phone_no,
						email_add,sync_state));
			}
		}
		
		/*UserObj uo = new UserObj(1,imeistring, tnumber, gmailacc, "0");
		
		SendUserToDatabase sd = new SendUserToDatabase(context,uo);
		sd.execute(new String[] { "http://tracker.demoplease.net/gpsUser.php" });*/
		
		/*if (isNetworkAvailable(context) && UserObjArr.size() > 0) {

			for (int i = 0; i < UserObjArr.size(); i++) {

				SendUserToDatabase sd = new SendUserToDatabase(context,
						UserObjArr.get(i));
				sd.execute(new String[] { "http://tracker.demoplease.net/gpsUser.php" });
			}

		}*/

		Cursor pndn_crsr = getDBdata(context);

		ArrayList<LocationObj> locationArr = new ArrayList<LocationObj>();

		int cur_size = pndn_crsr.getCount();

		if (pndn_crsr != null) {

			while (pndn_crsr.moveToNext()) {
				int _id = pndn_crsr.getInt(pndn_crsr.getColumnIndex("_id"));
				String longitude = pndn_crsr.getString(pndn_crsr
						.getColumnIndex("longitude"));
				String latitude = pndn_crsr.getString(pndn_crsr
						.getColumnIndex("latitude"));
				String device_time = pndn_crsr.getString(pndn_crsr
						.getColumnIndex("device_time"));
				String emi_number = pndn_crsr.getString(pndn_crsr
						.getColumnIndex("emi_number"));
				String sync_state = pndn_crsr.getString(pndn_crsr
						.getColumnIndex("sync_state"));

			/*	locationArr.add(new LocationObj(_id, longitude, latitude,
						device_time, emi_number, sync_state));*/
				

				/*if (isNetworkAvailable(context) && locationArr.size() > 0) {
					 JSONArray valuesarrayFinvHed = new JSONArray();
					 try {
						// Create values jsonObject
						JSONObject valuesJsonFinvHed = new JSONObject();
						valuesJsonFinvHed.put("longitude", longitude);
						valuesJsonFinvHed.put("latitude", latitude);
						valuesJsonFinvHed.put("eminumber", emi_number);
						valuesJsonFinvHed.put("repcode", "REP014");
						valuesJsonFinvHed.put("tpnumber", "94715274741");
						valuesJsonFinvHed.put("DbName", "DistNEW");
						arFinvHed.add(valuesJsonFinvHed
								.toString().trim());
					 }
					 catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
					 }
					}
				 else {
						if (!isNetworkAvailable(context)) {
							Log.e("","No Internet Connection Available");
						}
						// LocationChange(""+loc[0],""+loc[1],date_to_string,imeistring,"0");
					}
				
				ContentValues updateSynch = new ContentValues();
				updateSynch.put("sync_state", "1");
				mydb.update(LOCATION_DB,updateSynch,"_id ='"+ _id +"'", null);*/
			}
			
/*			if (pndn_crsr.getCount() <= 0) {
			}
			else{
				String strFH = arFinvHed.toString().trim();
				Log.e("json", "json created :" + strFH);
				HttpPost request = new HttpPost("http://123.231.13.199:1025/PDADBWebServiceN/PDADBWebServiceRest.svc/insertfRepGps");
				JSONStringer userJson = null;
				try {
					userJson = new JSONStringer().object()
							.key("fGps").value(strFH);
				} catch (Exception e) {
				}
				StringEntity entity = null;
				try {
					String format1 =  userJson.toString();
					format1 =  format1.replace("\\", "");
					format1 =  format1.replace("\"[{", "[{");
					format1 =  format1.replace("}]\"", "}]}");
					
					entity = new StringEntity(format1, "UTF-8");
				}
				catch (Exception e) {
				}
				
				entity.setContentEncoding(new BasicHeader(
						HTTP.CONTENT_TYPE, "application/json"));
				entity.setContentType("application/json");
				request.setEntity(entity);
				// Send request to WCF service
				DefaultHttpClient httpClient = new DefaultHttpClient();
				try {
					Log.e("response", "connect");
					HttpResponse response = httpClient.execute(request);
					// ===========================================================
					HttpEntity entitye = response.getEntity();
					is = entitye.getContent();
					if (is != null) {

						try {
							BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"), 8);
							sb = new StringBuilder();
							sb.append(reader.readLine() + "\n");
							String line = "0";
							while ((line = reader.readLine()) != null) {
								sb.append(line + "\n");
							}
							is.close();
							String result = sb.toString();
							Log.e("String Responce ","Print Responce 100 :" + result);
						} catch (Exception e1) {
							e1.printStackTrace();
						}
					}
					// ==================================
					Log.e("response", "response get 200 :" + response.toString());
					BufferedReader reader = new BufferedReader(
							new InputStreamReader(response.getEntity()
									.getContent(), "UTF-8"));
					String json = reader.readLine();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}*/
			
		}

	
		
		
		/*Log.e("Internet Connected ", "" + isNetworkAvailable(context));

		if (isNetworkAvailable(context) && locationArr.size() > 0) {

			for (int i = 0; i < locationArr.size(); i++) {

				SendLocationToDatabase sd = new SendLocationToDatabase(context,
						locationArr.get(i));
				sd.execute(new String[] { "http://tracker.demoplease.net/gpslogger.php" });
			}

		} else {
			if (!isNetworkAvailable(context)) {
				Toast toast = Toast.makeText(context,
						"No Internet Connection Available", Toast.LENGTH_SHORT);
				toast.show();
			}
			// LocationChange(""+loc[0],""+loc[1],date_to_string,imeistring,"0");
		}*/

	}

	private boolean isNetworkAvailable(Context context) {
		ConnectivityManager connectivityManager = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo activeNetworkInfo = connectivityManager
				.getActiveNetworkInfo();

		if (activeNetworkInfo != null
				&& activeNetworkInfo.isConnectedOrConnecting()) {
			return true;
		}
		return false;
	}

	private void LocationChange(String lng, String ltd, String time,
			String Emei, String syncstat) {

		try {

			Log.e("ltd", "" + lng);
			Log.e("lng", "" + ltd);
			Log.e("imeiNo", "" + imeistring);
			Log.e("timest", "" + date_to_string);

			ContentValues logBookSum = new ContentValues();
			logBookSum.put("longitude", "" + lng);
			logBookSum.put("latitude", "" + ltd);
			logBookSum.put("device_time", "" + time);
			logBookSum.put("emi_number", "" + Emei);
			logBookSum.put("sync_state", syncstat);

			mydb.insert(LOCATION_DB, null, logBookSum);
		} catch (Exception e) {
			Log.v("Error", "Data Log Error fRepGps " + e.toString());
		}
		mydb.close();
	}
	
	private void UserChange(String imei_no, String phone_no, String email_add, String syncstat) {

		try {

			ContentValues logBookSum = new ContentValues();
			logBookSum.put("imei_no", "" + imei_no);
			logBookSum.put("phone_no", "" + phone_no);
			logBookSum.put("email_add", "" + email_add);
			logBookSum.put("sync_state", syncstat);

			mydb.insert(USER_DB, null, logBookSum);
		} catch (Exception e) {
			Log.v("Error", "Data Log Error fUserGps " + e.toString());
		}
		mydb.close();
	}

	private void LocationUpdate(Context context, int _id) {
		mydb = context.openOrCreateDatabase(DATABASE_NAME,
				Context.MODE_PRIVATE, null);
		try {
			ContentValues newValues = new ContentValues();
			newValues.put("sync_state", "1");

			mydb.update(LOCATION_DB, newValues, "_id=" + _id, null);
			// mydb.delete(LOCATION_DB, "_id="+_id, null);

		} catch (Exception e) {
			Log.v("Error", "Update of fRepGps error " + e.toString());
		}
	}
	
	private void UserUpdate(Context context, int _id) {
		mydb = context.openOrCreateDatabase(DATABASE_NAME,
				Context.MODE_PRIVATE, null);
		try {
			ContentValues newValues = new ContentValues();
			newValues.put("sync_state", "1");

			mydb.update(USER_DB, newValues, "_id=" + _id, null);
			// mydb.delete(LOCATION_DB, "_id="+_id, null);

		} catch (Exception e) {
			Log.v("Error", "Update of fUserGps error " + e.toString());
		}
	}

	public class GetLocationNetGPS {

		Context mContext;

		private GetLocationNetGPS(Context mContext) {
			this.mContext = mContext;
		}

		private double[] GetLoc() {
			LocationManager lm = (LocationManager) mContext
					.getSystemService(Context.LOCATION_SERVICE);
			List<String> providers = lm.getProviders(true);

			/*
			 * Loop over the array backwards, and if you get an accurate
			 * location, then break out the loop
			 */
			Location l = null;

			for (int i = providers.size() - 1; i >= 0; i--) {
				l = lm.getLastKnownLocation(providers.get(i));
				if (l != null)
					break;
			}

			double[] gps = new double[2];
			if (l != null) {
				gps[0] = l.getLatitude();
				gps[1] = l.getLongitude();
			}
			return gps;
		}

	}

	public Location getLocation(Context context) {

		Location location = null;

		try {
			LocationManager locationManager = (LocationManager) context
					.getSystemService(Context.LOCATION_SERVICE);

			isGPSEnabled = locationManager
					.isProviderEnabled(LocationManager.GPS_PROVIDER);

			isNetworkEnabled = locationManager
					.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

			if (!isGPSEnabled && !isNetworkEnabled) {

			} else {
				this.canGetLocation = true;

				if (isGPSEnabled) {

					locationManager.requestLocationUpdates(
							LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES,
							MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
					Log.d("GPS Enabled", "GPS Enabled");
					if (locationManager != null) {
						location = locationManager
								.getLastKnownLocation(LocationManager.GPS_PROVIDER);
						if (location != null) {
							latitude = location.getLatitude();
							longitude = location.getLongitude();
						}
					}

				}

				else if (isNetworkEnabled) {
					
						locationManager.requestLocationUpdates(
								LocationManager.NETWORK_PROVIDER,
								MIN_TIME_BW_UPDATES,
								MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
						Log.d("Network", "Network");
						if (locationManager != null) {
							location = locationManager
									.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
							if (location != null) {
								latitude = location.getLatitude();
								longitude = location.getLongitude();
							}
						}
					
				}

			}

		} catch (Exception e) {
			e.printStackTrace();
		}

		return location;
	}

	private int getUserIsRegistered(Context context,String imei_no,String phone_no,String email_add) {
		mydb = context.openOrCreateDatabase(DATABASE_NAME,
				Context.MODE_PRIVATE, null);
		Cursor logregistered = null;
		try {
			String queryCheckifrgstrd = "SELECT * FROM fUserGps Where imei_no = '"+imei_no+"' And phone_no ='"+phone_no+"' And email_add ='"+email_add+"' ORDER BY _id ASC";
			logregistered = mydb.rawQuery(queryCheckifrgstrd, null);
		} catch (Exception e) {

		}

		return logregistered.getCount();
	}
	
	private Cursor getDBdata(Context context) {
		mydb = context.openOrCreateDatabase(DATABASE_NAME,
				Context.MODE_PRIVATE, null);
		Cursor logBookingMain = null;
		try {
			String queryCheckBooking = "SELECT * FROM fRepGps Where _id != '0' And sync_state ='0' ORDER BY _id ASC";
			logBookingMain = mydb.rawQuery(queryCheckBooking, null);
		} catch (Exception e) {

		}

		return logBookingMain;
	}
	
	private Cursor getDBdataUser(Context context) {
		mydb = context.openOrCreateDatabase(DATABASE_NAME,
				Context.MODE_PRIVATE, null);
		Cursor logBookingMain = null;
		try {
			String queryCheckBooking = "SELECT * FROM fUserGps Where _id != '0' And sync_state ='0' ORDER BY _id ASC";
			logBookingMain = mydb.rawQuery(queryCheckBooking, null);
		} catch (Exception e) {

		}

		return logBookingMain;
	}

	public class SendLocationToDatabase extends AsyncTask<String, Void, String> {

		private Context asynccontext;
		private LocationObj locObj;
		boolean exeptionTriggered = false;

		public SendLocationToDatabase(Context passContext, LocationObj location) {
			super();
			this.asynccontext = passContext;
			this.locObj = location;
			Log.e("Location Obj", locObj.getTime());
		}

		@Override
		protected String doInBackground(String... LoURL) {

			InputStream is = null;

			ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
			try {

				Date dateNow = new Date();
				Calendar c = Calendar.getInstance();
				SimpleDateFormat ddMMMyyFormat = new SimpleDateFormat(
						"yyyy-MM-dd HH:mm:ss");

				date_to_string = ddMMMyyFormat.format(dateNow);

				TelephonyManager telephonyManager = (TelephonyManager) asynccontext
						.getSystemService(Context.TELEPHONY_SERVICE);

				imeistring = telephonyManager.getDeviceId();

				List<NameValuePair> params = new ArrayList<NameValuePair>();
				/*
				 * params.add(new BasicNameValuePair("ltd", ""+loc[0]));
				 * params.add(new BasicNameValuePair("lng", ""+loc[1]));
				 * params.add(new BasicNameValuePair("imeiNo", imeistring));
				 * params.add(new BasicNameValuePair("timest", date_to_string));
				 */
				params.add(new BasicNameValuePair("ltd", "" + locObj.getLtd()));
				params.add(new BasicNameValuePair("lng", "" + locObj.getLng()));
				params.add(new BasicNameValuePair("imeiNo", locObj.getEmei()));
				params.add(new BasicNameValuePair("timest", locObj.getTime()));

				Log.e("ltd", "" + locObj.getLtd());
				Log.e("lng", "" + locObj.getLng());
				Log.e("imeiNo", "" + locObj.getEmei());
				Log.e("timest", "" + locObj.getTime());

				HttpParams httpParameters = new BasicHttpParams();
				HttpClient httpclient = new DefaultHttpClient(httpParameters);

				/* HttpPost httppost = new HttpPost(RegisterUserLink); */
				HttpPost httppost = new HttpPost(LoURL[0]);
				JSONObject json = new JSONObject();

				json.put("ltd", locObj.getLtd());
				json.put("lng", locObj.getLng());
				json.put("imeiNo", locObj.getEmei());
				json.put("timest", locObj.getTime());

				JSONArray postjson = new JSONArray();
				postjson.put(json);
				httppost.setHeader("json", json.toString());
				httppost.getParams().setParameter("jsonpost", postjson);
				httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
				HttpResponse httpResponse = httpclient.execute(httppost);

				HttpEntity httpEntity = httpResponse.getEntity();

				is = httpEntity.getContent();

			} catch (UnsupportedEncodingException e) {
				exeptionTriggered = true;
				e.printStackTrace();
			} catch (ClientProtocolException e) {
				exeptionTriggered = true;
				e.printStackTrace();
			} catch (IOException e) {
				exeptionTriggered = true;
				e.printStackTrace();
			} catch (JSONException e) {
				exeptionTriggered = true;
				e.printStackTrace();
			}

			try {
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(is, "iso-8859-1"), 8);
				StringBuilder sb = new StringBuilder();

				String line = null;

				while ((line = reader.readLine()) != null) {
					// sb.append(line+"n");
					sb.append(line);
				}
				is.close();

			} catch (Exception e) {
				Log.e("Buffer Error", "Error converting result" + e.toString());
				exeptionTriggered = true;
			}

			return null;
		}

		@Override
		protected void onPostExecute(String result) {
			// LocationChange(""+loc[0],""+loc[1],date_to_string,imeistring,"1");
			if (exeptionTriggered == false) {
				Log.e("Location Obj _id", "" + locObj.get_id());
				LocationUpdate(asynccontext, locObj.get_id());
			}

		}

	}
	
	public class SendUserToDatabase extends AsyncTask<String, Void, String> {

		private Context asynccontext;
		private UserObj usrObj;
		boolean exeptionTriggered1 = false;

		public SendUserToDatabase(Context passContext, UserObj usrObj) {
			super();
			this.asynccontext = passContext;
			this.usrObj = usrObj;
		}

		@Override
		protected String doInBackground(String... LoURL) {

			InputStream is = null;

			ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
			try {

				Date dateNow = new Date();
				Calendar c = Calendar.getInstance();
				SimpleDateFormat ddMMMyyFormat = new SimpleDateFormat(
						"yyyy-MM-dd HH:mm:ss");

				date_to_string = ddMMMyyFormat.format(dateNow);

				TelephonyManager telephonyManager = (TelephonyManager) asynccontext
						.getSystemService(Context.TELEPHONY_SERVICE);

				imeistring = telephonyManager.getDeviceId();

				List<NameValuePair> params = new ArrayList<NameValuePair>();

				params.add(new BasicNameValuePair("imei_no", "" + usrObj.getImei_no()));
				params.add(new BasicNameValuePair("phone_no", "" + usrObj.getPhone_no()));
				params.add(new BasicNameValuePair("email_add", usrObj.getEmail_add()));

				HttpParams httpParameters = new BasicHttpParams();
				HttpClient httpclient = new DefaultHttpClient(httpParameters);

				/* HttpPost httppost = new HttpPost(RegisterUserLink); */
				HttpPost httppost = new HttpPost(LoURL[0]);
				JSONObject json = new JSONObject();

				json.put("imei_no", usrObj.getImei_no());
				json.put("phone_no", usrObj.getPhone_no());
				json.put("email_add", usrObj.getEmail_add());

				JSONArray postjson = new JSONArray();
				postjson.put(json);
				httppost.setHeader("json", json.toString());
				httppost.getParams().setParameter("jsonpost", postjson);
				httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
				HttpResponse httpResponse = httpclient.execute(httppost);

				HttpEntity httpEntity = httpResponse.getEntity();

				is = httpEntity.getContent();

			} catch (UnsupportedEncodingException e) {
				exeptionTriggered1 = true;
				e.printStackTrace();
			} catch (ClientProtocolException e) {
				exeptionTriggered1 = true;
				e.printStackTrace();
			} catch (IOException e) {
				exeptionTriggered1 = true;
				e.printStackTrace();
			} catch (JSONException e) {
				exeptionTriggered1 = true;
				e.printStackTrace();
			}

			try {
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(is, "iso-8859-1"), 8);
				StringBuilder sb = new StringBuilder();

				String line = null;

				while ((line = reader.readLine()) != null) {
					// sb.append(line+"n");
					sb.append(line);
				}
				is.close();

			} catch (Exception e) {
				Log.e("Buffer Error", "Error converting result" + e.toString());
				exeptionTriggered1 = true;
			}

			return null;
		}

		@Override
		protected void onPostExecute(String result) {
			// LocationChange(""+loc[0],""+loc[1],date_to_string,imeistring,"1");
			if (exeptionTriggered1 == false) {
				Log.e("Location Obj _id", "" + usrObj.get_id());
				isNotRegistered = false;
				UserUpdate(asynccontext, usrObj.get_id());
			}

		}

	}

	@Override
	public void onLocationChanged(Location location) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onProviderEnabled(String provider) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onProviderDisabled(String provider) {
		// TODO Auto-generated method stub

	}
	
	 private static Account getAccount(AccountManager accountManager) {
		    Account[] accounts = accountManager.getAccountsByType("com.google");
		    Account account;
		    if (accounts.length > 0) {
		      account = accounts[0];      
		    } else {
		      account = null;
		    }
		    return account;
		  }

}
